22. Scope Rules: Who Knows About What

A complete C program need not be compiled all at once; the source text of the program may be kept in several files, and previously compiled routines may be loaded from libraries. How do we arrange that data gets passed from one routine to another? We have already seen how to use function arguments and values, so let us talk about external data. Warning: the words declaration and definition are used precisely in this section; don’t treat them as the same thing.

A major shortcut exists for making extern declarations. If the definition of a variable appears BEFORE its use in some function, no extern declaration is needed within the function. Thus, if a file contains

f1( )  ... 

int foo;

f2( )  ... foo = 1; ... 

f3( )  ... if ( foo ) ... 

no declaration of foo is needed in either f2 or or f3, because the external definition of foo appears before them. But if f1 wants to use foo, it has to contain the declaration

f1( ) 

extern int foo;

...

This is true also of any function that exists on another file — if it wants foo it has to use an extern declaration for it. (If somewhere there is an extern declaration for something, there must also eventually be an external definition of it, or you’ll get an ``undefined symbol’’ message.)

There are some hidden pitfalls in external declarations and definitions if you use multiple source files. To avoid them, first, define and initialize each external variable only once in the entire set of files:

int foo 0;

You can get away with multiple external definitions on UNIX, but not on GCOS, so don’t ask for trouble. Multiple initializations are illegal everywhere. Second, at the beginning of any file that contains functions needing a variable whose definition is in some other file, put in an extern declaration, outside of any function:

extern int foo;

f1( )  ... 

etc.

The #include compiler control line, to be discussed shortly, lets you make a single copy of the external declarations for a program and then stick them into each of the source files making up the program.